import type { StoreData } from "@/Interface/AiCmpInterface";
import CryptoJS from "crypto-js";


// 工具函数：生成稳定哈希值
export const generateDataHash = (stores: StoreData[]) => {
  const serialized = JSON.stringify(stores);
  return CryptoJS.MD5(serialized).toString();
};


// 鉴权工具函数
export const generateAuthUrl = () => {
  const API_KEY = import.meta.env.VITE_SPARK_APIKEY;
  const API_SECRET = import.meta.env.VITE_SPARK_APISECRET;
  // 服务信息
  const host = "spark-api.xf-yun.com";
  const path = "/v3.5/chat";

  // 1. 生成RFC1123格式时间戳
  const date = new Date().toUTCString();

  // 2. 构造签名原始字符串
  const tmp = `host: ${host}\ndate: ${date}\nGET ${path} HTTP/1.1`;

  // 3. 生成HMAC-SHA256签名
  const hash = CryptoJS.HmacSHA256(tmp, API_SECRET);

  // 4. Base64编码签名
  const signature = CryptoJS.enc.Base64.stringify(hash);

  // 5. 构造authorization原始字符串
  const authorizationOrigin = `api_key="${API_KEY}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`;

  // 6. 二次Base64编码
  const authorization = CryptoJS.enc.Base64.stringify(
    CryptoJS.enc.Utf8.parse(authorizationOrigin)
  );

  // 7. URL编码参数
  const encodedParams = new URLSearchParams({
    authorization,
    date,
    host
  }).toString();

  // 8. 构造最终URL
  return `wss://${host}${path}?${encodedParams}`;
};